/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package isvp.implementations;

import isvp.constants.ComponentConstants;
import isvp.constants.ExceptionConstants;
import isvp.constants.ISVPConstants;
import isvp.exceptions.ComponentException;
import isvp.exceptions.ISVPException;
import isvp.interfaces.ISVP;
import isvp.interfaces.Privilege;
import isvp.utilities.ISVPUtils;
import isvp.utilities.XMLUtils;
import java.io.File;
import java.io.IOException;
import java.util.TreeMap;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 *
 * @author jjophin
 */
public class ISVPFactory {
    
    /**
     * Returns the implementations of the ISVP components
     * @param file
     * @return
     * @throws ISVPException 
     */
    public static ISVP getISVPImplementation(File file) throws ISVPException {
        ISVP isvpInstance = null;
        try {
            isvpInstance = new ISVPImpl(file);
        } catch (ComponentException ex) {
            throw new ISVPException(ex.getMessage());
        } catch (IOException ex) {
            throw new ISVPException(ExceptionConstants.ISVP_READ_EXCEPTION);
        }
        return isvpInstance;
    }
    
    public static ApplicationImpl getApplicationImplementation(ISVP currentISVP) throws ComponentException {
        String appFileName = ISVPUtils.getComponentFileName(currentISVP, ISVPConstants.APPLICATION);
        Document applicationXML = ISVPUtils.getComponentDocument(currentISVP, appFileName, ISVPConstants.APPLICATION);
        return new ApplicationImpl(applicationXML, appFileName);
    }
    
    public static TreeMap getPrivilegesImplementation(ISVP currentISVP) throws ComponentException {
        TreeMap privileges = new TreeMap();
        String privilegeFileName = ISVPUtils.getComponentFileName(currentISVP, ISVPConstants.PRIVILEGES);
        Document privilegesXML = ISVPUtils.getComponentDocument(currentISVP, privilegeFileName, ISVPConstants.PRIVILEGES);
        NodeList privilegeList = XMLUtils.getXMLNodes(privilegesXML, ComponentConstants.PRIVILEGEDATA_XPATH);
        int privilegeCount = privilegeList.getLength();
        for(int i=0; i<privilegeCount; i++) {
            Node privilegeNode = privilegeList.item(i);
            Privilege newPrivilege = new PrivilegeImpl(privilegeNode, privilegeFileName);
            privileges.put(newPrivilege.getPrivilegeName(), newPrivilege);
        }        
        return privileges;
    } 
}
